package com.isoft.config;

import com.isoft.service.UserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.sql.DataSource;

/**
 * @author LiuGaoMing
 * @version 1.0
 * @description:
 * @date 2024/5/16 10:54
 */
//@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private UserDetailServiceImpl userDetailService;


    /**
     * 创建并配置JdbcTokenRepositoryImpl实例作为token存储的bean。
     * 这个方法不接受任何参数，因为它直接依赖于外部定义的数据源dataSource。
     *
     * @return JdbcTokenRepositoryImpl 一个配置好的JdbcTokenRepositoryImpl实例，
     *         用于存储和检索OAuth2令牌。
     */
    @Bean
    public JdbcTokenRepositoryImpl tokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        // 设置数据源为外部定义的dataSource，以便JdbcTokenRepositoryImpl可以使用它进行数据库操作。
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 1，内存身份认知
         */
//        加密密码器,单项hash，
//        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
////        bug，拦截不到lgm下的vip，他也能进vip了
//        auth.inMemoryAuthentication().passwordEncoder(encoder)
//                .withUser("lgm").password(encoder.encode("1234")).roles("common")
//                .and()
//                .withUser("vip").password(encoder.encode("1234")).roles("vip","common");
        /**
         * 2,JDBC身份认证
         */
//        编码
//        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//        String userSQL = "select username,password,valid from t_customer where username = ?";
//        String authoritySQL = "select c.username,a.authority from t_customer c, t_authority a , t_customer_authority ca " +
//                "where ca.customer_id = c.id and ca.authority_id = a.id and c.username = ?";
//        auth.jdbcAuthentication().passwordEncoder(encoder)
//                .dataSource(dataSource)
//                .usersByUsernameQuery(userSQL)
//                .authoritiesByUsernameQuery(authoritySQL);
        /**
         * 3，UserDetailsService身份验证
         */
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        auth.userDetailsService(userDetailService).passwordEncoder(encoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

            http.authorizeHttpRequests().antMatchers("/")
                    .permitAll()
                    .antMatchers("/img/**").permitAll()
                    .antMatchers("/login/**").permitAll()
                    .antMatchers("/movie/common/**").hasRole("common")
                    .antMatchers("/movie/vip/**").hasRole("vip")
                    .anyRequest().authenticated();

            http.formLogin()
                    .loginPage("/userLogin").permitAll()
                    .usernameParameter("name")
                    .passwordParameter("password")
                    .defaultSuccessUrl("/")
                    .failureUrl("/userLogin?error")
                    ;
            http.logout().logoutUrl("/mylogout")
                    .logoutSuccessUrl("/userLogin");
            http.rememberMe().rememberMeParameter("rememberme")
                    .tokenValiditySeconds(200)
                    .tokenRepository(tokenRepository());
            http.csrf().disable();
    }


}
